package com.queclink.ycm.handler;

import com.alibaba.fastjson.JSONObject;
import com.queclink.ycm.common.utils.DataUtil;
import com.queclink.ycm.common.utils.DateUtil;
import com.queclink.ycm.container.NettyClients;
import com.queclink.ycm.model.ChannelSession;
import com.queclink.ycm.model.NettyClient;
import com.queclink.ycm.proto.ProtocolTpUtility;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jim.li
 * @email jim.li@queclink.com
 * @date 2022-01-10 09:23:00
 */
public class GatewayInBoundHandler extends SimpleChannelInboundHandler<byte[]> {

    private int port;

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public GatewayInBoundHandler(int port) {
        this.port = port;
    }

    private static final Logger log = LoggerFactory.getLogger(GatewayInBoundHandler.class);

    private AttributeKey<ChannelSession> attributeKey = AttributeKey.valueOf("ChannelSession");

    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    public static Integer getAtomic() {
        return atomicInteger.get();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

//    @Override
//    public void channelInactive(ChannelHandlerContext ctx) {
//        NettyClient nettyClient = NettyClients.getByCtx(ctx);
//        String s = nettyClient.getUniqueId();
//        if (!StringUtils.isEmpty(nettyClient.getUniqueId())) {
//            System.out.println("==========超时关闭通道=============");
//            //更新设备在线状态
//            updateDeviceStatus(nettyClient.getUniqueId());
//            NettyClients.delete(nettyClient.getUniqueId());
//            NettyClient.remove(ctx);
//        }
//    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        atomicInteger.incrementAndGet();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        atomicInteger.decrementAndGet();
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
        String msgString = new String(msg, CharsetUtil.UTF_8);
        System.out.println(DateUtil.getNowFormatDate() + " [TCP]" + msgString);

        // 收到消息直接打印输出
        System.out.println(ctx.channel().remoteAddress() + " Say : " + msgString);
        HashMap<String, Object> map = new HashMap<>();
        InetSocketAddress ipSocket = (InetSocketAddress)ctx.channel().remoteAddress();
        String clientIP = ipSocket.getAddress().getHostAddress();
        int devicePort = ipSocket.getPort();
        String CLIENT_IP = clientIP + ":" + devicePort;
        map.put("ip", CLIENT_IP);
        map.put("port", this.port);
        log.info("设备端ip地址：" + clientIP);
//        if (msgString.equals("AT+GTQMS=0$")) {
//            JSONObject jsono = new JSONObject(true);
//            jsono.put("count", NettyClient.client.size());
//            jsono.put("time", DataUtil.getNowFormatDate());
//            ctx.writeAndFlush(jsono.toJSONString().getBytes());
//            System.out.println(DataUtil.getNowFormatDate()+"[发送数据]"+jsono.toJSONString().getBytes());
//            return;
//        }
//        if (msgString.equals("2B00000D0A")) {
//            List<Map<String, Object>> list = MyTask.list;
//            JSONObject jsono = new JSONObject(true);
//            jsono.put("list", list);
//            ctx.writeAndFlush(jsono.toJSONString().getBytes());
//            System.out.println(DataUtil.getNowFormatDate()+"[发送数据]"+jsono.toJSONString().getBytes());
//            return;
//        }
        //解析获取的报文
        String[] msgArray = msgString.split(",");
        //解析得到报文的类型
        String[] msgTypeArray = msgArray[0].split(":");
        //解析得到报文序列号
        String receiveMsg = msgArray[msgArray.length - 1];

        // 回sack
        if (this.port == port) {
            String ack = "";
//            if (msgTypeArray[1].equals("GTHBD")) {
//                ack = "+SACK:GTHBD,," + receiveMsg;
//                // ctx.writeAndFlush();
//            } else {
//                // 返回客户端消息 - 我已经接收到了你的消息
//                ack = "+SACK:" + receiveMsg;
//            }
            System.out.println(DataUtil.getNowFormatDate() + " [发送数据]" + ack);
            ctx.writeAndFlush(ack.getBytes());
        }
        //协议
        ProtocolTpUtility.distributed(ctx, msgString, attributeKey, map);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object object) throws Exception {
        if (object instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) object).state();
            if (IdleState.READER_IDLE.equals(state)) {
                //关闭channel
                NettyClient nettyClient = NettyClients.getByCtx(ctx);
                if (!StringUtils.isEmpty(nettyClient.getUniqueId())) {
                    System.out.println("==========超时关闭通道=============");
                    //更新设备在线状态
//                    updateDeviceStatus(nettyClient.getUniqueId());
                    NettyClients.delete(nettyClient.getUniqueId());
                }
                channels.remove(ctx.channel());
                ctx.channel().close();
                System.out.println("Disconnect");
            }
        } else {
            super.userEventTriggered(ctx, object);
        }
    }

//    /**
//     * 更新设备状态为离线
//     *
//     * @param imei
//     */
//    public void updateDeviceStatus(String imei) {
//        if (imei != null) {
//            String url = PlatfromServerConstant.getRemoveDevice();
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("imei", imei);
//            HttpRequestUtils.doPostByJson(url, jsonObject);
//            System.out.println("成功更改设备状态");
//        } else {
//            System.out.println("更改设备在线状态IMEI不能为空");
//        }
//    }
}
